package net.yunxinyong.sign.service.impl;

import net.yunxinyong.sign.aop.CECException;
import net.yunxinyong.sign.entity.*;
import net.yunxinyong.sign.mapper.CecBaseMapper;
import net.yunxinyong.sign.mapper.CecFiveMapper;
import net.yunxinyong.sign.mapper.EcnomicInventoryMapper;
import net.yunxinyong.sign.service.CecBaseService;
import net.yunxinyong.sign.service.CecFiveSerivce;
import net.yunxinyong.sign.service.CecOneService;
import net.yunxinyong.sign.service.RecordService;
import net.yunxinyong.sign.utils.ListUtils;
import org.apache.ibatis.annotations.Mapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.Date;
import java.util.List;

@Service
@Transactional(propagation = Propagation.REQUIRED, rollbackFor = CECException.class)
public class CecFiveSerivceImpl implements CecFiveSerivce {
    @Autowired
    private CecFiveMapper cecFiveMapper;
    @Autowired
    private RecordService recordService;
    @Autowired
    private CecBaseMapper cecBaseMapper;
    @Autowired
    private CecBaseService cecBaseService;
    @Autowired
    private CecOneService cecOneService;
    @Autowired
    private EcnomicInventoryMapper ecnomicInventoryMapper;
    @Override
    public CecFive select(int invid) {
        CecFiveExample cecFiveExample = new CecFiveExample();
        //id和企业状态为正常作为查询条件
        cecFiveExample.createCriteria().andInvIdEqualTo(invid).andStatusEqualTo(0);
        List<CecFive> list = cecFiveMapper.selectByExample(cecFiveExample);
        if (!list.isEmpty()) {
            return list.get(0);
        }
        return null;
    }

    @Override
    public void update(CecFive cecFive, Integer adminId) {
        cecFive.setUpdateTime(new Date());
        //往5表更新数据的时候，同时往base表的194项更新数据
        Integer update = baseAndFiveLogic1(cecFive);
        //1表和5表的表间关系
        fiveAndOneLogic(cecFive);
        int count = cecFiveMapper.updateByPrimaryKey(cecFive);
        boolean insert = recordService.insert(adminId, cecFive.getInvId(), null, 12);
        if (count <= 0||!insert || update <= 0 ) {
            throw new CECException(501, "更新失败!");
        }
    }

    @Override
    public void insert(CecFive cecFive, Integer adminId) {
        cecFive.setUpdateTime(new Date());
        cecFive.setCreateTime(new Date());
        cecFive.setStatus(0);
        //往5表更新数据的时候，同时往base表的194项更新数据
        Integer update = baseAndFiveLogic1(cecFive);
        //1表和5表的表间关系
        fiveAndOneLogic(cecFive);
        int count = cecFiveMapper.insert(cecFive);
        boolean insert = recordService.insert(adminId, cecFive.getInvId(), null, 12);
        if (count <= 0||!insert || update <= 0) {
            throw new CECException(501, "添加失败!");
        }
    }

    /**
     * 5表和一表的逻辑关系  往5表更新数据的时候，同时往base表的194项更新数据
     * @param cecFive
     * @return
     */
    public Integer baseAndFiveLogic1(CecFive cecFive){
        CecBase cecBase = cecBaseService.select(cecFive.getInvId());
        if (cecBase != null){
            //往5表更新数据的时候，同时往base表的194项更新数据
            //base 表数据
            // `non_unit_expenditure` decimal(20,5) DEFAULT NULL COMMENT '(194)非企业法人单位支出(单位：千元)',
            //  `non_unit_total_assets` decimal(20,5) DEFAULT NULL COMMENT '(194)非企业法人单位资产总计(单位：千元)',
            //5表数据
            //`total_assets` decimal(20,2) DEFAULT NULL COMMENT '(14)资产总计 ',
            //`total_expenditure` decimal(20,2) DEFAULT NULL COMMENT '(21)本年支出合计
            cecBase.setNonUnitExpenditure(cecFive.getTotalExpenditure());
            cecBase.setNonUnitTotalAssets(cecFive.getTotalAssets());
            return cecBaseMapper.updateByPrimaryKeySelective(cecBase);
        }else {
            throw new CECException(502,"请先填写base表");
        }
    }

    /**
     * 611-1表和611-5表的逻辑 611-1表产业收入之和（支出）>=法人财务数据，不大于10%（611-1的非经营性单位支出 >= 611-5表21本年支出合计，不大于10%）
     * @param cecFive
     */
    public void fiveAndOneLogic(CecFive cecFive){
        EcnomicInventoryExample ecnomicInventoryExample = new EcnomicInventoryExample();
        ecnomicInventoryExample.createCriteria().andIdEqualTo((long)cecFive.getInvId());
        List<EcnomicInventory> ecnomicInventories = ecnomicInventoryMapper.selectByExample(ecnomicInventoryExample);
        if (!ListUtils.isEmpty(ecnomicInventories)){
            EcnomicInventory ecnomicInventory = ecnomicInventories.get(0);
            //只有底册中type包含1 表时，才进行和1表的逻辑审核    这样做视为了防止 企业在 提交base表 之后 填写了部分的表 重新修改表类型，这时新分配的表是不包含 1表的。
            if (ecnomicInventory.getType() != null && ecnomicInventory.getType().contains("1")){
                List<CecOne> cecOneList = cecOneService.get(cecFive.getInvId());
                if (!ListUtils.isEmpty(cecOneList)){
                    //1表的 非经营性单位支出
                    BigDecimal oneNonBussineseIncome = new BigDecimal(0);
                    for (CecOne cecOne : cecOneList){
                        if (cecOne.getNonBussineseIncome() != null && !cecOne.getNonBussineseIncome().equals("") ){
                            oneNonBussineseIncome = oneNonBussineseIncome.add(new BigDecimal(cecOne.getNonBussineseIncome()));
                        }
                    }
                    BigDecimal totalExpenditure = cecFive.getTotalExpenditure();
                    boolean logic = !(totalExpenditure != null && oneNonBussineseIncome.compareTo(totalExpenditure) >= 0 ) || !(totalExpenditure!= null && totalExpenditure.multiply(new BigDecimal(1.1)).compareTo(oneNonBussineseIncome) >= 0);
                    if(logic){
                        throw new CECException(502,"您填写的数据有误，611-1的 12项 非经营性单位支出应该 >= 611-5表21项 本年支出合计，且不大于10%");
                    }
                }

            }
        }
    }
}
